package com.huifaapp.mall.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huifaapp.mall.R;
import com.huifaapp.mall.adapter.DetailsofPaymentListviewAdapter;
import com.huifaapp.mall.adapter.DetailsofPaymenthongbaoAdapter;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.base.bean.PayBean;
import com.huifaapp.mall.bean.CouponListBean;
import com.huifaapp.mall.bean.DetailsBalance;
import com.huifaapp.mall.bean.DetailsPayShoppingCart;
import com.huifaapp.mall.bean.GoodsListBean;
import com.huifaapp.mall.bean.GoodsSkuCountBean;
import com.huifaapp.mall.bean.MinuteKillGetSpecialTime;
import com.huifaapp.mall.bean.OrdersCalactualMoney;
import com.huifaapp.mall.bean.PayDetails;
import com.huifaapp.mall.bean.PayNumber;
import com.huifaapp.mall.bean.UserMyShoppingCart;
import com.huifaapp.mall.bean.UsersAddrVoBean;
import com.huifaapp.mall.bean.UsersPayDefult;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.AlipayUtils;
import com.huifaapp.mall.uitils.Contig;
import com.huifaapp.mall.uitils.ToastUtil;
import com.huifaapp.mall.uitils.UtilsImage;
import com.huifaapp.mall.view.AmountView;
import com.huifaapp.mall.view.PosterWin;
import com.huifaapp.mall.view.TakePhotoPopWin;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.squareup.okhttp.Request;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class DetailsofPaymentActivity extends AppCompatActivity implements TakePhotoPopWin.OnItemClickListener,PosterWin.OnItemClickListener{

    private TextView tv_Consignee_Name;
    private TextView tv_Consignee_phone;
    private TextView tv_Consignee_Address;
    private ImageView iv_goodsImage;
    private TextView tv_PayDetails_goodsName;
    private TextView tv_PayDetails_ColorSize;
    private TextView tv_PayDetails_price;
    private TextView tv_PayDetails_pricebefore;
    private TextView tv_PayDetails_count;
    public static TextView tv_PayDetails_couponAmount;
    private TextView tv_PayDetails_pointsAmount;

//    private PullToRefreshListView mylv_detailspayment;
    private LinearLayout ll_detailspayment_ac;
    private AmountView amount_view_pay;
    private LinearLayout ll_num;
    static TextView tv_detailpay_price;

    double couponAmount=0;
    static double pointsAmount=0;
    private View.OnClickListener onClickListener;

    private TextView tv_detailpay_settlement;
    private RelativeLayout main_view;
    WindowManager.LayoutParams params;
    TakePhotoPopWin mPop;
    public static PosterWin mPopposter;
    private Switch switch_details_payment;
    PayDetails list;
    static double total;
    int count;
    private ImageView iv_details_payment_back;
    private LinearLayout ll_details_payment_address;
    String name,phone,city;
   public static String orderNo;
    ArrayList<GoodsListBean> goodsListBean;
    static ArrayList<String> listSkuidCount;
    private LinearLayout ll_details_pay_shopping;
    private LinearLayout LinearLayout_personset;
    private ArrayList<CouponListBean> couponlistbean;
    static int isUserPoint=0;
    static int point;
    static String adressid="";
    static double totalAmount;
    private LinearLayout ll_wudizhi;
    static EditText et_detailpay_liuyan;
    private LinearLayout ll_huijingbi;
    String intent;

    //  double pointsAmount;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detailsof_payment);
        listSkuidCount=getIntent().getStringArrayListExtra("listSkuidCount");
        intent=getIntent().getStringExtra("intent");

        tv_Consignee_Name= (TextView) findViewById(R.id.tv_Consignee_Name);
        tv_Consignee_phone= (TextView) findViewById(R.id.tv_Consignee_phone);
        tv_Consignee_Address= (TextView) findViewById(R.id.tv_Consignee_Address);
        iv_goodsImage= (ImageView) findViewById(R.id.iv_goodsImage);
        tv_PayDetails_goodsName= (TextView) findViewById(R.id.tv_PayDetails_goodsName);
        tv_PayDetails_ColorSize= (TextView) findViewById(R.id.tv_PayDetails_ColorSize);
        tv_PayDetails_price= (TextView) findViewById(R.id.tv_PayDetails_price);
        tv_PayDetails_pricebefore= (TextView) findViewById(R.id.tv_PayDetails_pricebefore);
        tv_PayDetails_count= (TextView) findViewById(R.id.tv_PayDetails_count);
        tv_PayDetails_couponAmount= (TextView) findViewById(R.id.tv_PayDetails_couponAmount);
        tv_PayDetails_pointsAmount= (TextView) findViewById(R.id.tv_PayDetails_pointsAmount);
//        mylv_detailspayment= (PullToRefreshListView) findViewById(R.id.mylv_detailspayment);
        LinearLayout_personset= (LinearLayout) findViewById(R.id.LinearLayout_personset);

        ll_detailspayment_ac= (LinearLayout) findViewById(R.id.ll_detailspayment_ac);
        ll_num= (LinearLayout) findViewById(R.id.ll_num);
        tv_detailpay_price= (TextView) findViewById(R.id.tv_detailpay_price);
        tv_detailpay_settlement= (TextView) findViewById(R.id.tv_detailpay_settlement);
        main_view= (RelativeLayout) findViewById(R.id.main_view);
        switch_details_payment= (Switch) findViewById(R.id.switch_details_payment);
        iv_details_payment_back= (ImageView) findViewById(R.id.iv_details_payment_back);
        ll_details_pay_shopping= (LinearLayout) findViewById(R.id.ll_details_pay_shopping);
        ll_wudizhi= (LinearLayout) findViewById(R.id.ll_wudizhi);
        et_detailpay_liuyan= (EditText) findViewById(R.id.et_detailpay_liuyan);
        ll_huijingbi= (LinearLayout) findViewById(R.id.ll_huijingbi);
        iv_details_payment_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                listSkuidCount.clear();
                Contig.couponId="";
            }
        });
        ll_details_payment_address= (LinearLayout) findViewById(R.id.ll_details_payment_address);
        ll_details_payment_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(DetailsofPaymentActivity.this,ReceiveAddressActivity.class);
                startActivityForResult(intent,1021);
            }
        });
        ll_wudizhi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(DetailsofPaymentActivity.this,ReceiveAddressActivity.class);
                startActivityForResult(intent,1021);
            }
        });
        loadPayDetail();
        amount_view_pay = (AmountView)findViewById(R.id.amount_view_pay);
        amount_view_pay.setOnAmountChangeListener(new AmountView.OnAmountChangeListener() {
            @Override
            public void onAmountChange(View view, int amount) {
//                loadPayNumber(amount);
//                tv_detailpay_price.setText("¥"+total%count*amount);
                count=amount;
                Loadkucun(goodsListBean.get(0).getGoodsId());
                listSkuidCount.add(goodsListBean.get(0).getGoodsId()+":"+count);
                Order(DetailsofPaymentActivity.this);

            }
        });
        Loadbalance();
        Loadbalance();
        Loadbalance();
        mPop=new TakePhotoPopWin(this);
        mPop.setOnItemClickListener(this);
        mPop.setFocusable(false);
        Order(DetailsofPaymentActivity.this);

            findViewById(R.id.tv_detailpay_settlement).setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Log.e("数据","地址====="+adressid+"");
                    if("".equals(adressid)||"null".equals(adressid)){
                        Toast.makeText(DetailsofPaymentActivity.this, "地址不能为空，请选择地址", Toast.LENGTH_SHORT).show();
                    }else {
                        submitOrder(DetailsofPaymentActivity.this);
                        //设置PopupWindow中的位置
                        mPop.showAtLocation(DetailsofPaymentActivity.this.findViewById(R.id.main_view), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//                params = getWindow().getAttributes();
//                //当弹出Popupwindow时，背景变半透明
//                params.alpha=0.7f;
//                getWindow().setAttributes(params);
                    }
                }
            });

        // 添加监听
        switch_details_payment.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){//开启
                    isUserPoint=1;

                    Order(DetailsofPaymentActivity.this);
//                                total= paydetails.getTotalAmount()- paydetails.getPointsAmount();
//                                tv_detailpay_price.setText("¥"+total);
                }else {//关闭
                    isUserPoint=0;
                    Order(DetailsofPaymentActivity.this);
//                  tv_detailpay_price.setText("¥"+total);
                }
            }
        });


//        et_detailpay_liuyan.addTextChangedListener(new TextWatcher() {
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                // 输入的内容变化的监听
//                Log.e("输入过程中执行该方法", "文字变化");
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                // 输入后的监听
//                Log.e("输入结束执行该方法", "输入结束");
//            }
//
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count,
//                                          int after) {
//                // 输入前的监听
//                Log.e("输入前确认执行该方法", "开始输入");
//
//            }
//
//
//        });
    }
    private void Loadkucun(String goodsId){
        Log.e("ShopCartActivity","库存url========="+ ApiManager.GOODS_SKU_COUNT+"?skuId="+goodsId);
        OkHttpUtils.get().url(ApiManager.GOODS_SKU_COUNT+"?skuId="+goodsId).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                GoodsSkuCountBean listskucount = gson.fromJson(response,GoodsSkuCountBean.class);
                amount_view_pay.setGoods_storage(listskucount.getData());
            }
        });
    }
    //手机返回键
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        listSkuidCount.clear();
        Contig.couponId="";
    }
    String method = "1"; //支付方式 1 微信支付，2支付宝支付。
    @Override
    public void setOnItemClick(View v) {
        switch (v.getId()){
            case R.id.tv_true_pay:
//                params = getWindow().getAttributes();
//                params.alpha=1f;
//                getWindow().setAttributes(params);
                mPop.dismiss();
                pay();
                break;
            case R.id.ll_ye_pay:
//
                break;
            case R.id.ll_wx_pay:
                method="1";
                break;
            case R.id.ll_zfb_pay:
                method="2";
                break;
            case R.id.ll_fq_pay:

                break;
            case R.id.ll_ye_pay_no:

                break;
            case  R.id.iv_pay_close:
                mPop.dismiss();
                break;
        }
    }

    private void pay(){

        if ("1".equals(method)) {
            String url = ApiManager.WXPAY_PAY+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+AUniqueIdentifier.getDeviceId(DetailsofPaymentActivity.this)+"&orderNo="+orderNo;
//            String url = ApiManager.WXPAY_PAY+"?token=201712291124171334f3ed61d93e05404b8dc78f10c4770cf8&appId=D7B72681-8205-4C8F-8CCB-142C448203E3"
//                    +"&orderNo="+orderNo;
            Log.e("WEB", "路径Pay=====" + url);
            HttpUtils http = new HttpUtils();
            http.send(HttpRequest.HttpMethod.POST, url, new RequestCallBack<String>() {
                @Override
                public void onLoading(long total, long current, boolean isUploading) {
//                  testTextView.setText(current + "/" + total);
                    Log.e("数据", "数据-------" + current + "/" + total);
                }

                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
//                    textView.setText(responseInfo.result);

                    try {
                        Log.e("数据123", "数据payd-------" + responseInfo.result);
                        Gson gson = new Gson();
                        PayBean list = gson.fromJson(responseInfo.result, PayBean.class);

                        if(list.getCode().equals("10000")) {
                            Log.e("数据123", "数据list-------" + list);
                            IWXAPI mWxApi = WXAPIFactory.createWXAPI(DetailsofPaymentActivity.this, list.getData().getAppid(), true);
                            mWxApi.registerApp(list.getData().getAppid());
                            PayReq req = new PayReq();
                            req.appId = list.getData().getAppid();
                            req.partnerId = list.getData().getMch_id();
                            req.prepayId = list.getData().getPrepay_id();
                            req.nonceStr = list.getData().getNonce_str();
                            req.timeStamp = list.getData().getTimestamp();
                            req.packageValue ="Sign=WXPay";
                            req.sign = list.getData().getSign();
                            //在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                            Log.e("数据123", "数据payd-------" + req);
                            mWxApi.sendReq(req);
                            Log.e("数据123", "mWxApi-------" + mWxApi);
                        }else{
                            Toast.makeText(DetailsofPaymentActivity.this,list.getMsg(),Toast.LENGTH_SHORT).show();
                        }
                    }catch (JsonSyntaxException e){
                        Toast.makeText(DetailsofPaymentActivity.this,"未知错误",Toast.LENGTH_LONG).show();
                    }

            }
                @Override
                public void onStart() {
                }

                @Override
                public void onFailure(HttpException error, String msg) {
                }
            });
        } else if ("2".equals(method)) {
            new AlipayUtils(DetailsofPaymentActivity.this).getAlipaySignature(orderNo,SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN),AUniqueIdentifier.getDeviceId(DetailsofPaymentActivity.this));
        } else {
            ToastUtils.showShortSafe("获取信息失败!");
        }
    }

    /**
     * 余额
     */
    private void Loadbalance(){
        Log.e("余额","  "+ApiManager.USERS_BALANCE
                +"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)
                +"&appId="+ AUniqueIdentifier.getDeviceId(DetailsofPaymentActivity.this));
        OkHttpUtils.get().url(ApiManager.USERS_BALANCE
                +"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)
                +"&appId="+ AUniqueIdentifier.getDeviceId(DetailsofPaymentActivity.this)).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                DetailsBalance list = gson.fromJson(response, DetailsBalance.class);
                if(list.getCode().equals("10000")) {
                    Log.e("余额", list.getData().getBalance() + "            " + totalAmount);
                    if (totalAmount > list.getData().getBalance()) {
                        //余额不足
                        Contig.yue = 1;
                        Contig.balance = list.getData().getBalance();
                    } else {
                        Contig.yue = 2;
                        Contig.balance = list.getData().getBalance();
                    }
                }else if(list.getCode().equals("10001")){
                    Toast.makeText(DetailsofPaymentActivity.this,list.getMsg(),Toast.LENGTH_SHORT).show();
//                    Intent intent=new Intent(DetailsofPaymentActivity.this,LoginActivity.class);
//                    startActivity(intent);
                }else{
                    Toast.makeText(DetailsofPaymentActivity.this,list.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    public static void Order(final Context context){
        StringBuffer permission = new StringBuffer();
        for(int i=0;i<listSkuidCount.size();i++){
            if(i == 0){
                permission.append(listSkuidCount.get(i));
            }else{
                permission.append(","+listSkuidCount.get(i));
            }
        }
        Log.e("支付JI","url=============="+ApiManager.OEDERS_CALACTUALMONEY+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)
                +"&appId="+AUniqueIdentifier.getDeviceId(context)
                +"&skuIdCounts="+permission.toString()
                +"&couponId="+Contig.couponId
                +"&isUsePoint="+isUserPoint
                +"&pointCout="+total
                +"&expressFee="+"");
        OkHttpUtils.get().url(ApiManager.OEDERS_CALACTUALMONEY+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)
                +"&appId="+AUniqueIdentifier.getDeviceId(context)
                +"&skuIdCounts="+permission.toString()
                +"&couponId="+Contig.couponId
                +"&isUsePoint="+isUserPoint
                +"&pointCout="+total
                +"&expressFee="+"")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {

                    }
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject obj=new JSONObject(response);
                            Log.e("","response==="+response);
                            if(obj.getString("code").equals("10000")){
                                OrdersCalactualMoney  list=OrdersCalactualMoney.newInstanceDetails(obj.getString("data"));
                                tv_detailpay_price.setText("¥"+list.getActualPay());
                                Contig.datatotal=list.getActualPay();
                                totalAmount=list.getActualPay();
                            }else if(obj.getString("code").equals("10001")){
//                                Intent intent=new Intent(context,LoginActivity.class);
//                                context.startActivity(intent);
                            }else{
                                Toast.makeText(context,obj.getString("msg"),Toast.LENGTH_SHORT).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    public static void submitOrder(final Context context){
        StringBuffer permission = new StringBuffer();
        for(int i=0;i<listSkuidCount.size();i++){
            if(i == 0){
                permission.append(listSkuidCount.get(i));
            }else{
                permission.append(","+listSkuidCount.get(i));
            }
        }
        Log.e("支付","url=============="+ApiManager.BASE_NIUPAI_URL+"userspay/submitOrder"
                +"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)
                +"&appId="+AUniqueIdentifier.getDeviceId(context)
                +"&skuIdCounts="+permission.toString()
                +"&couponId="+Contig.couponId
                +"&isUsePoints="+isUserPoint
                +"&id="+adressid
                +"&actualMoney="+totalAmount
                +"&point="+point
                +"&deducMoney="+pointsAmount
                +"&bugMsg="+et_detailpay_liuyan.getText().toString()
                +"&expressFee="+"");
        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"userspay/submitOrder"
                +"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)
                +"&appId="+AUniqueIdentifier.getDeviceId(context)
                +"&skuIdCounts="+permission.toString()
                +"&couponId="+Contig.couponId
                +"&isUsePoints="+isUserPoint
                +"&id="+adressid
                +"&actualMoney="+totalAmount
                +"&point="+point
                +"&deducMoney="+pointsAmount
                +"&bugMsg="+et_detailpay_liuyan.getText().toString()
                +"&expressFee="+"")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject obj=new JSONObject(response);
                            if(obj.getString("code").equals("10000")){
                                orderNo=obj.getString("data");
                                Contig.orderNo=orderNo;
                            }else if(obj.getString("code").equals("10001")){
//                                Intent intent=new Intent(context,LoginActivity.class);
//                                context.startActivity(intent);
                            }else{
                                Toast.makeText(context,obj.getString("msg"),Toast.LENGTH_SHORT).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent event){
        if(mPop!=null&&mPop.isShowing()){
            return false;
        }
        return super.dispatchTouchEvent(event);
    }





    ArrayList<String> skuIdCounts=new ArrayList<>();
    String urls ;
    private void loadPayDetail(){


        StringBuffer permission = new StringBuffer();
        for(int i=0;i<listSkuidCount.size();i++){
            if(i == 0){
                permission.append(listSkuidCount.get(i));
            }else{
                permission.append(","+listSkuidCount.get(i));
            }
    }
      Log.e("数据q",ApiManager.USERSPAY_PAYDETAIL+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+ AUniqueIdentifier.getDeviceId(DetailsofPaymentActivity.this)+"&skuIdCounts="+permission.toString());
//        Log.e("数据",ApiManager.USERSPAY_PAYDETAIL+"?token=2017121117473013488a1208548b1f422cb1bcbe4fc56c9501&appId=5B489793-3521-4043-95C4-9F98C6B02E47&skuIdCounts=3560266:5,4370580:2");
//        for (int i=0;i<goodsListBean.size();i++) {
        urls=ApiManager.USERSPAY_PAYDETAIL+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+ AUniqueIdentifier.getDeviceId(DetailsofPaymentActivity.this)+"&skuIdCounts="+permission.toString();
//        }
        OkHttpUtils.get().url(urls).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject obj=new JSONObject(response);
                    if(obj.getString("code").equals("10000")) {
                        String data = obj.getString("data");
                        final PayDetails paydetails=PayDetails.newInstanceDetails(data);
                        totalAmount = paydetails.getTotalAmount();
                        UsersAddrVoBean addrvobean=UsersAddrVoBean.newInstanceDetails(paydetails.getUsersAddrVo());
                        if(addrvobean.getReceiverName().equals("")&&(Contig.name.equals("")||Contig.phone.equals("")||Contig.city.equals(""))){
                            ll_wudizhi.setVisibility(View.VISIBLE);
                            ll_details_payment_address.setVisibility(View.GONE);
                        }else{
                            ll_wudizhi.setVisibility(View.GONE);
                            ll_details_payment_address.setVisibility(View.VISIBLE);

                            if(Contig.name.equals("")||Contig.phone.equals("")||Contig.city.equals("")) {
                                tv_Consignee_Name.setText(addrvobean.getReceiverName());
                                tv_Consignee_phone.setText(addrvobean.getReceiverPhone());
                                tv_Consignee_Address.setText(addrvobean.getDetail());
                            }else{
                                tv_Consignee_Name.setText(Contig.name);
                                tv_Consignee_phone.setText(Contig.phone);
                                tv_Consignee_Address.setText(Contig.city);
                            }
                            adressid=addrvobean.getId();
                        }
//                        Contig.datatotal=paydetails.getCompareAmount();
                        goodsListBean=GoodsListBean.newInstanceList(paydetails.getGoodsList());
                        couponlistbean = CouponListBean.newInstanceList(paydetails.getCouponList());
                        Contig.couponlistbean=couponlistbean;

                        Log.e("优惠券","couponlistbean===="+paydetails.getIsUseSysCoupon());
                        if(paydetails.getIsUseSysCoupon().equals("1")){
                            LinearLayout_personset.setVisibility(View.VISIBLE);
                            if (couponlistbean.size()<=0) {
//                                Toast.makeText(DetailsofPaymentActivity.this, "暂无可用红包", Toast.LENGTH_SHORT).show();
                                LinearLayout_personset.setVisibility(View.GONE);

                            } else {
                                LinearLayout_personset.setVisibility(View.VISIBLE);
                                LinearLayout_personset.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                        Order(DetailsofPaymentActivity.this);
                                        Log.e("是付款",Contig.datatotal+"");
                                        mPopposter=new PosterWin(DetailsofPaymentActivity.this);
                                        mPopposter.setOnItemClickListener(DetailsofPaymentActivity.this);
                                        mPopposter.setFocusable(false);
                                        mPopposter.setList(couponlistbean);
                                        mPopposter.showAtLocation(DetailsofPaymentActivity.this.findViewById(R.id.main_view), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                                    }
                                });
                            }
                        }else if(paydetails.getIsUseSysCoupon().equals("0")){
                            LinearLayout_personset.setVisibility(View.GONE);
                        }
                        if(paydetails.getIsUsePoint().equals("1")){
                            ll_huijingbi.setVisibility(View.VISIBLE);
                        }else if(paydetails.getIsUsePoint().equals("0")){
                            ll_huijingbi.setVisibility(View.GONE);
                        }
//                      LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) mylv_detailspayment.getLayoutParams();
//                      //获取当前控件的布局对象
//                      params.height=goodsListBean.size()*280;//设置当前控件布局的高度
//                      mylv_detailspayment.setLayoutParams(params);//将设置好的布局参数应用到控件中

                        if(intent.equals("xq")){
                            listSkuidCount.clear();
                            ll_detailspayment_ac.setVisibility(View.VISIBLE);
//                            mylv_detailspayment.setVisibility(View.GONE);
                            UtilsImage.uploadimageview(iv_goodsImage,goodsListBean.get(0).getGoodsImg(),null,DetailsofPaymentActivity.this);
                            goodsListBean.get(0).getGoodsId();
                            tv_PayDetails_goodsName.setText(goodsListBean.get(0).getGoodsName());
                            if (goodsListBean.get(0).getParam() == ""||goodsListBean.get(0).getParam() == "null"||goodsListBean.get(0).getParam() == null) {
                                tv_PayDetails_ColorSize.setText("");
                            }else {
                            String parem=goodsListBean.get(0).getParam().substring(1,goodsListBean.get(0).getParam().length())
                                    .substring(0,goodsListBean.get(0).getParam().length()-2);
                                        tv_PayDetails_ColorSize.setText(parem);
//
                            }
                            if (goodsListBean.get(0).getIsRevice().equals("0")){
                                tv_PayDetails_pricebefore.setVisibility(View.GONE);
                                tv_PayDetails_price.setText("¥"+goodsListBean.get(0).getOrginPrice());
                            }else {
                                tv_PayDetails_price.setText("¥" + goodsListBean.get(0).getPrice());
                                tv_PayDetails_pricebefore.setText("¥" + goodsListBean.get(0).getOrginPrice());
                                tv_PayDetails_pricebefore.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                            }
//                            tv_PayDetails_count.setText("x "+goodsListBean.get(0).getCount());
                            count=goodsListBean.get(0).getCount();
                            listSkuidCount.add(goodsListBean.get(0).getGoodsId()+":"+count);
                        }else if(intent.equals("gwc")){
                            ll_detailspayment_ac.setVisibility(View.GONE);
                            createShopItem(ll_details_pay_shopping,goodsListBean);
//                            mylv_detailspayment.setVisibility(View.VISIBLE);
//                            DetailsofPaymentListviewAdapter adapter = new DetailsofPaymentListviewAdapter(DetailsofPaymentActivity.this, goodsListBean);
//                            mylv_detailspayment.setAdapter(adapter);
                        }

                        point=paydetails.getPoints();
                        pointsAmount=paydetails.getPointsAmount();

//                    tv_PayDetails_count.setText("x "+paydetails.getCount());
                    tv_PayDetails_couponAmount.setText("请选择");
                    tv_PayDetails_pointsAmount.setText("可用"+paydetails.getPoints()+"惠金币抵用"+paydetails.getPointsAmount()+"元");
                    couponAmount=paydetails.getCouponAmount();
                    pointsAmount = paydetails.getPointsAmount();
                    tv_detailpay_price.setText("¥"+paydetails.getTotalAmount());
                    total=paydetails.getTotalAmount();


                        Contig.couponId=paydetails.getCouponIds();
//                        submitOrder();
                    }else if(obj.getString("code").equals("10002")){
                        Intent intent=new Intent(DetailsofPaymentActivity.this,LoginActivity.class);
                        startActivity(intent);
                    }else {
                        Toast.makeText(DetailsofPaymentActivity.this,obj.getString("msg"),Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void createShopItem(ViewGroup viewGroup, List<GoodsListBean> list){
        if (list == null){
            return;
        }
        viewGroup.removeAllViews();
        for (int i = 0 ;i<list.size();i++){
            GoodsListBean attr =list.get(i);
           View convertView = LayoutInflater.from(this).inflate(R.layout.detailsofpay_listview, null);
            DetailsofPaymentListviewAdapter.ViewHolder viewHolder = new DetailsofPaymentListviewAdapter.ViewHolder(convertView);
            viewHolder.setdate(DetailsofPaymentActivity.this,list.get(i));
            viewGroup.addView(convertView);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
try{

            if (requestCode == 1021) {
                name = data.getStringExtra("names");

                phone = data.getStringExtra("phones");
                city = data.getStringExtra("citys");
                adressid = data.getStringExtra("ids");
                if(name.equals("")){
                    ll_wudizhi.setVisibility(View.VISIBLE);
                    ll_details_payment_address.setVisibility(View.GONE);

                }
                ll_wudizhi.setVisibility(View.GONE);
                ll_details_payment_address.setVisibility(View.VISIBLE);
                Contig.name = name;
                Contig.phone = phone;
                Contig.city = city;
                tv_Consignee_Name.setText(name);
                tv_Consignee_phone.setText(phone);
                tv_Consignee_Address.setText(city);
            }

        }
        catch (Exception e){
            Log.e("数据",e.getMessage());
        }
        }

}
